package com.lagou.edu.factory;

import com.lagou.edu.component.ComponentScan;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 * 工厂类，生产对象（使用反射技术）
 */
public class BeanFactory {

    /**
     * 任务一：读取解析xml，通过反射技术实例化对象并且存储待用（map集合）
     * 任务二：对外提供获取实例对象的接口（根据id获取）
     */
    private static Map<String,Object> map = new ConcurrentHashMap<>();  // 存储对象

    private static volatile BeanFactory beanFactory;

    private final String DEFAULT_FILE = "beans.xml";

    private BeanFactory() {
        try {
            Element rootElement = initBean(DEFAULT_FILE);
            setBeanProperties(rootElement);
            component();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public static BeanFactory getInstance() {
        if (beanFactory == null) {
            synchronized (BeanFactory.class) {
                if (beanFactory == null) {
                    beanFactory = new BeanFactory();
                }
            }
        }
        return beanFactory;
    }

    /**
     * 初始化bean对象
     *
     * @param filePath
     * @throws DocumentException
     * @throws ClassNotFoundException
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    private static Element initBean(String filePath) throws DocumentException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        // 任务一：读取解析xml，通过反射技术实例化对象并且存储待用（map集合）
        // 加载xml
        InputStream resourceAsStream = BeanFactory.class.getClassLoader().getResourceAsStream(filePath);
        // 解析xml
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(resourceAsStream);
        Element rootElement = document.getRootElement();
        List<Element> beanList = rootElement.selectNodes("//bean");
        for (int i = 0; i < beanList.size(); i++) {
            Element element =  beanList.get(i);
            // 处理每个bean元素，获取到该元素的id 和 class 属性
            String id = element.attributeValue("id");
            String clazz = element.attributeValue("class");
            // 通过反射技术实例化对象
            Class<?> aClass = Class.forName(clazz);
            Object o = aClass.newInstance();  // 实例化之后的对象
            // 存储到map中待用
            map.put(id,o);
        }
        return rootElement;
    }


    /**
     * 设置bean对象属性
     * @param root
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    private static void setBeanProperties(Element root) throws InvocationTargetException, IllegalAccessException {
        // 实例化完成之后维护对象的依赖关系，检查哪些对象需要传值进入，根据它的配置，我们传入相应的值
        // 有property子元素的bean就有传值需求
        List<Element> propertyList = root.selectNodes("//property");
        // 解析property，获取父元素
        for (int i = 0; i < propertyList.size(); i++) {
            Element element =  propertyList.get(i);   //
            int flag = 0;
            String name = element.attributeValue("name");
            String ref = element.attributeValue("ref");
            String value = element.attributeValue("value");

            if (! value.isEmpty()) {
                flag = 1;
            }

            // 找到当前需要被处理依赖关系的bean
            Element parent = element.getParent();

            // 调用父元素对象的反射功能
            String parentId = parent.attributeValue("id");
            Object parentObject = map.get(parentId);
            // 遍历父对象中的所有方法，找到"set" + name
            Method[] methods = parentObject.getClass().getMethods();
            for (int j = 0; j < methods.length; j++) {
                Method method = methods[j];
                if(method.getName().equalsIgnoreCase("set" + name)) {
                    if (flag == 0)
                        method.invoke(parentObject,map.get(ref));
                    else
                        method.invoke(parentObject, value);
                }
            }
            // 把处理之后的parentObject重新放到map中
            map.put(parentId,parentObject);
        }
    }


    public Object getBean(String id) {
        return map.get(id);
    }

    /**
     * 扫描
     */
    private void component() {
        map.entrySet().forEach( entry -> {
            Object object = entry.getValue();
            if (object instanceof ComponentScan) {
                ComponentScan componentScan = (ComponentScan) object;
                try {
                    componentScan.scanBean(map);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return;
            }
        });
    }
}
